package service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import component.sender.AdvertiseSender;
import dao.AdvertisementDao;
import dto.AdSpaceDto;
import pojo.Advertisement;
import pojo.Merchant;
import service.AdvertisementService;
import util.JsonUtil;

@Service
@Transactional
public class AdvertisementServiceImpl implements AdvertisementService {

	@Resource(name="advertiseSender")
	private AdvertiseSender advertiseSender;
	
	@Resource(name="advertisementDaoImpl")
	private AdvertisementDao advertisementDao;
	
	@Override
	public List<Advertisement> findAll(String mId) {
		return advertisementDao.findAll(mId);
	}

	@Override
	public Advertisement update(String id, String status, String mId) {
		return advertisementDao.update(id, status, mId);
	}

	@Override
	public Advertisement save(Advertisement ad, String mId) {
		return advertisementDao.save(ad, mId);
	}

	public int sendJms(String msg){
		return advertiseSender.send(msg);
	}
	
	@Override
	public String sendJms(Advertisement ad,Merchant merchant, String date, String time) {
		String start=null;
		String end=null;
		Date startTime = null; 
		Date endTime = null;
		if(time.equals("1")){
			 start = date+" 00:00:00";
			 end = date+" 08:00:00";
		}
		if(time.equals("2")){
			 start = date+" 08:00:00";
			 end = date+" 16:00:00";
		}
		if(time.equals("3")){
			start = date+" 16:00:00";
			end = date+" 24:00:00";
		}
		
		try {
			 startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(start);
			 endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(end);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		ad.setMerchant(merchant);
		ad.setStartTime(startTime);
		ad.setEndTime(endTime);
		ad.setStatus("sended");
		
		
			
		if(advertisementDao.save(ad, merchant.getId())!=null){
			AdSpaceDto adDto = new AdSpaceDto();
			adDto.setId(ad.getId());
			adDto.setImgPath(ad.getImgPath());
			adDto.setAdPrice(ad.getAdPrice());
			adDto.setStartTime(ad.getStartTime());
			adDto.setEndTime(ad.getEndTime());
			adDto.setFoodId(ad.getFoodId());
			adDto.setmName(merchant.getName());
			adDto.setMid(merchant.getId());
			adDto.setStartTime(startTime);
			adDto.setEndTime(endTime);
			System.out.println(JsonUtil.toJsonString(adDto));
			if(sendJms(JsonUtil.toJsonString(adDto))==1)
			{return "jms success";}
			return "jms fail";
		}
		else{
			return "save fail";
		}
	}

	@Override
	public List<Advertisement> findByStatus(String mId, String status) {
		return advertisementDao.findByStatus(mId, status);
	}

	@Override
	public Advertisement findById(String id) {
		return advertisementDao.findById(id);
	}

}
